package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Country;

 
@Stateless
public class CountryService {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Country getById(Integer id){	
		return em.find(Country.class, id);
	}
	
    public Country save(Country country) {
    	em.persist(country); 
    	return country;
    }
    
    public Country update(Country country) {
    	return em.merge(country);
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Country.class, id));	
    }
    
    @SuppressWarnings("unchecked")
    public List<Country> list(int first, int max) {    	
		Query query = em.createQuery("SELECT e FROM Country e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
	public Country getByPhoneCode(Integer phonecode) {
		Country result = null;
    	Query query = em.createQuery("SELECT e FROM Country e WHERE e.phonecode=:phonecode");
    	query.setParameter("phonecode", phonecode);
		try {
			result = (Country) query.getSingleResult(); 
        }
    	catch (Exception e) {
		}
        return result; 
	}
	
	public Country getByIsoCode(String isocode) {
		Country result = null;
    	Query query = em.createQuery("SELECT e FROM Country e WHERE e.isocode=:isocode");
    	query.setParameter("isocode", isocode);
		try {
			result = (Country) query.getSingleResult(); 
        }
    	catch (Exception e) {
		}
        return result; 
	}
    
    
}

